package com.qunar.train.mock.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringUtil implements ApplicationContextAware {

    public ApplicationContext appContext;

    public SpringUtil() {
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return ContextHolder.instance.appContext.getBean(name, requiredType);
    }

    public void setApplicationContext(ApplicationContext appContext) {
        ContextHolder.instance.appContext = appContext;
    }

    private static class ContextHolder {
        private static final SpringUtil instance = new SpringUtil();
    }

    public static <T> T getBean(Class<T> requiredType) {
        String beanName = "";
        String className = requiredType.getSimpleName();
        if (!isBlank(className)) {
            beanName = new StringBuffer(className.length()).append(Character.toLowerCase(className.charAt(0)))
                    .append(className.substring(1)).toString();
        }
        return getBean(beanName, requiredType);
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

}
